<template>
  <div class="mod-blog__tag">
    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="tag_input" size="small"
      @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">
      + New Tag
    </el-button>
    <div class="tagAndInput" v-for="(tag, index) in dynamicTags" :key="tag.id">
      <el-tag ref="tagRefs" closable :disable-transitions="false" @close="handleClose(tag.id)"
        @dblclick.prevent="handleUpdate(tag, index)">
        {{ tag.name }}
      </el-tag>
    </div>
    <ChyDrawer v-model="drawerOpen" title="修改标签" @confirm="handleUpdateOver">
      <el-input v-model="inputTagValue" />
    </ChyDrawer>

  </div>
</template>

<script setup lang='ts'>
import { nextTick, ref, onMounted } from 'vue'
import { ElInput, ElTag } from 'element-plus'
import { addBlogTag, getBlogTag, updateBlogTag, deleteBlogTag } from '@/api/blogTag'
import ChyDrawer from '@/components/chy-drawer'
const inputValue = ref('')
interface ITag {
  id: string,
  name: string,
}
const dynamicTags = ref<Array<ITag>>([])
const tagRefs = ref<InstanceType<typeof ElTag>[]>([])

const getTagList = () => {
  getBlogTag().then((res: any) => {
    dynamicTags.value = res.data.list
  })
}
getTagList()

const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
const handleClose = (id: string) => {
  deleteBlogTag(id).then((res: any) => {
    if (res.code === 0) {
      dynamicTags.value?.splice(dynamicTags.value?.findIndex(ele => ele.id === id) as number, 1)
    }
  })
}

const drawerOpen = ref(false)
const inputTagValue = ref('')
const tagId = ref('')
const handleUpdate = (tag: ITag, index: number) => {
  drawerOpen.value = true
  tagId.value = tag.id
  inputTagValue.value = tag.name
}

const handleUpdateOver = () => {
  let params = {
    id: tagId.value,
    name: inputTagValue.value
  }
  updateBlogTag(params).then((res: any) => {
    if (res.code === 0) {
      // dynamicTags.value[index].name = inputTagValue.value
      drawerOpen.value = false
      getTagList()
    }
  })
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    addBlogTag({ name: inputValue.value }).then((res: any) => {
      if (res.code === 0) {
        getTagList()
      }
    })
  }
  inputVisible.value = false
  inputValue.value = ''
}

onMounted(() => {
})
</script>

<style lang='scss' scoped>
.mod-blog__tag {
  display: flex;
  flex-wrap: wrap;

  .el-button {
    margin-top: 5px;
  }

  .el-tag {
    margin-right: 5px;
    margin-top: 5px;
    cursor: pointer;
    user-select: none;
  }

  .tag_input,
  .button-new-tag {
    width: 80px;
    margin-right: 5px;
  }
}
</style>
